#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QCoreApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    pThread = nullptr;


    ui->pushButton_StopSend->setDisabled(true);

    connect(ui->pushButton_StartSend, &QPushButton::clicked, this, &MainWindow::startSendMsgSlot);

    connect(ui->pushButton_StopSend, &QPushButton::clicked, this, &MainWindow::stopSendMsgSlot);

}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::modifyMsg(QString text)
{
    text.replace(u8" ", "");

    QString replacement = ui->lineEdit_instandByte->text();

    text.replace(ui->spinBox_StartByte->text().toUInt(), replacement.length(), replacement);

    return text;
}

void MainWindow::startSendMsgSlot()
{
    pThread = new QThread(this);

    pUdpObject = new UdpInterface;

    pUdpObject->setHeaderLen(ui->lineEdit_HeaderLen->text().toUInt());

    connect(ui->lineEdit_HeaderLen, &QLineEdit::textChanged, this, [&](){
        pUdpObject->setHeaderLen(ui->lineEdit_HeaderLen->text().toUInt());
    });

    connect(this, &MainWindow::stopSendSignal, pUdpObject, &UdpInterface::stopSend);

    connect(ui->pushButton_Modify, &QPushButton::clicked, this, [&](){

        QString newText = modifyMsg(ui->textEdit_initBytes->toPlainText());
        pUdpObject->setHeaderLen(ui->lineEdit_HeaderLen->text().toUInt());

        QCoreApplication::processEvents();
        ui->textBrowser_SendBytes->setText(newText);
        pUdpObject->setMsgData(ui->textBrowser_SendBytes->toPlainText().toUtf8());
    });

    ui->textBrowser_SendBytes->setText(ui->textEdit_initBytes->toPlainText());

    pUdpObject->setMsgData(ui->textBrowser_SendBytes->toPlainText().toUtf8());

    if(!pUdpObject->bindNet(ui->lineEdit_LocalIP->text(), ui->lineEdit_LocalPort->text().toUInt())) {
        QMessageBox::warning(this, u8"警告", u8"本地IP地址端口绑定无效！请检查IP地址和端口");
        return;
    }

    if (!pUdpObject->setRemoteObject(ui->lineEdit_RemoteIP->text(), ui->lineEdit_RemotePort->text().toUInt())) {
        QMessageBox::warning(this, u8"警告", u8"远端IP地址无效！请检查远端IP地质");
        return;
    }

    ui->pushButton_StartSend->setDisabled(true);

    ui->pushButton_StopSend->setEnabled(true);

    pUdpObject->moveToThread(pThread);

    pThread->start();
}

void MainWindow::bindNetworkSlot()
{

}

void MainWindow::stopSendMsgSlot()
{
    emit stopSendSignal();
    pThread->quit();
    pThread->wait();
    delete pThread;
    pThread = nullptr;
    ui->pushButton_StartSend->setEnabled(true);
    ui->pushButton_StopSend->setDisabled(true);
}


